package com.smart.wap.h5;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.smart.common.entities.ajax.AjaxResult;
import com.smart.common.entities.constant.SmartConstant;
import com.smart.common.entities.core.BaseSearch;
import com.smart.common.entities.core.Page;
import com.smart.common.entities.domain.LoginResult;
import com.smart.manager.member.entities.models.MemberProfileMain;
import com.smart.manager.member.entities.models.query.QMemberProfileMain;
import com.smart.manager.member.repository.MemberProfileMainRepository;
import com.smart.manager.union.egg.models.UnionEggOrder;
import com.smart.manager.weixin.mp.handler.WxmpHandler;
import com.smart.manager.weixin.mp.repository.WxmpAccountRepository;
import com.smart.utils.MemberAcl;
import com.smart.utils.MemberStp;
import com.smart.wap.bodys.WxmpBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Api(tags = "移动端-收货地址")
@RestController
@RequestMapping(SmartConstant.WAP_API_PREFIX + "h5/open")
@RequiredArgsConstructor
@Log4j2
public class OpenControll {

    private final WxmpAccountRepository wxmpAccountRepository;

    private final WxmpHandler wxmpHandler;

    @ApiOperation(value = "检测Token是否有效")
    @GetMapping(value = "checkAccessToken")
    @SaCheckLogin(type = MemberStp.TYPE)
    public AjaxResult<String> checkAccessToken(BaseSearch baseSearch) {


        return AjaxResult.success();
    }


    @ApiOperation(value = "获取站点配置信息")
    @PostMapping("getSiteConfig")
    public AjaxResult<JSONObject> getSiteConfig(Boolean mock) {
        String wxmpAppId = wxmpAccountRepository.getDefaultAppId();
        JSONObject result = JSONObject.of("wxmpAppId", wxmpAppId);

        if (mock) {
            String accessToken = MemberAcl.login(1745464869476212736L);
            result.put("accessToken", accessToken);
        }

        return AjaxResult.data(result);

    }

    @ApiOperation(value = "获取页面Ticket")
    @PostMapping("getPageTicket")
    public AjaxResult<WxJsapiSignature> getPageTicket(@Validated @RequestBody WxmpBody.TicketBody body) {
        WxJsapiSignature result = wxmpHandler.getPageTicket(body);
        return AjaxResult.data(result);

    }


    @GetMapping(value = "loginByCode/{appId}/{code}")
    @ApiOperation(value = "根据公众号TOKEN登录")
    public AjaxResult<LoginResult> getTokenByCode(@PathVariable String appId, @PathVariable String code) {

        LoginResult result = new LoginResult();
        WxOAuth2UserInfo info = wxmpHandler.getMpUserInfo(appId, code);
        MemberProfileMain profileMain = new QMemberProfileMain().wxMpId.eq(info.getOpenid()).setMaxRows(1).findOne();
        if (ObjectUtil.isNull(profileMain)) {
            result.setSuccess(false);
            return AjaxResult.data(result);
        }
        String accessToken = MemberAcl.login(profileMain.getId());
        result.setSuccess(true).setOpenId(info.getOpenid()).setAccessToken(accessToken);

        StringBuilder updateFlag = new StringBuilder();

        if (!StrUtil.startWith(profileMain.getAvatar(), "http")) {
            profileMain.setAvatar(info.getHeadImgUrl());
            updateFlag.append("1");
        }

        if (StrUtil.startWith(profileMain.getNickName().toUpperCase(), "WTB")) {
            profileMain.setNickName(info.getNickname());
            updateFlag.append("1");
        }
        Opt.ofBlankAble(updateFlag.toString()).ifPresent(x -> profileMain.update());
        return AjaxResult.data(result);
    }

}
